<?php
require_once 'class_Jabber.php';
require_once 'SVNBot/SVN/Updater.php';
require_once 'SVNBot/Logger/Debug.php';

class SVNBot_Bot
{
	public function __construct($config) 
	{
		$this->_config = $config;

		$this->_initUpdater($this->_config->repository, $this->_config->checkout);
		$this->_initJabber();

		// enter main loop
		$this->_jabber->connect($this->_config->server);
		$this->_jabber->execute(60);
	}

	private function _initUpdater() 
	{
		$this->_updater = new SVNBot_SVN_Updater($this->_config->repository, $this->_config->checkout, $this->_config->svnpath);
		$this->_updater->addLogger($this);
		$this->_updater->addLogger(new SVNBot_Logger_Debug);
	}

	private function _initJabber() 
	{
		$this->_jabber = new Jabber(true);
		$this->_jabber->set_handler('connected', $this, 'connected');
		$this->_jabber->set_handler('authenticated', $this, 'authenticated');
		$this->_jabber->set_handler('heartbeat', $this, 'heartbeat');
		$this->_jabber->set_handler('message_normal', $this, 'message');
		$this->_jabber->set_handler('message_chat', $this, 'message');
		$this->_jabber->set_handler('msgevent_composing_stop', $this, 'dummy');
		$this->_jabber->set_handler('msgevent_composing_start', $this, 'dummy');
		$this->_jabber->set_handler('debug_log', new SVNBot_Logger_Debug, 'log');
	}

	public function dummy() 
	{

	}

	public function connected() 
	{
		$this->_jabber->login($this->_config->login, $this->_config->password);
	}

	public function authenticated() 
	{
		$this->_jabber->browse();
		$this->_jabber->get_roster();
		$this->_jabber->set_presence('', 'Ready to serve');
	}

	public function heartbeat() 
	{
		$this->_updater->update();
	}

	public function log($msg) 
	{
		foreach ($this->_jabber->roster as $jid => $details) {
			$this->_jabber->message($jid, 'chat', null, $msg);
		}
	}

	public function message($from, $to, $body, $subject, $thread, $id, $extended) 
	{
		$msg = <<<MSG
Broadcast message from: $from
Subject: $subject

$body
MSG;
		foreach ($this->_jabber->roster as $jid => $details) {
			$this->_jabber->message($jid, 'chat', null, $msg);
		}
	}

	public function disconnected() 
	{
		$this->_jabber->connect($this->_config->server);
		$this->_jabber->execute(60);
	}
}
